from django.shortcuts import render, redirect
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django import http

# 读取配置文件中的参数（settings/dev.py）
from django.conf import settings
from dj_shop.utils.responseCode import RESP_CODE
# 查询用户需要的models
from oauth.models import OauthQQUser
# 调用django。已绑定userid和openid直接登录
from django.contrib.auth import login
# url反向解析
from django.urls import reverse

# 引入itsdangerous，可以将字符串加密,之前的版本序列化字符串很长：TimedJSONWebSignatureSerializer
from itsdangerous import TimedSerializer

# 引用utils公共包下的jwtToken生成器
from dj_shop.utils.jwtGenerate import GenerateOpenidToken,TokenToJson

import logging

logger = logging.getLogger('django')


# Create your views here.

# QQ登录扫码页面接口
class QQAuthUrlView(View):
    def get(self, request):
        # 接收next
        print("QQAuthUrlView-reuest:", request)
        next = request.GET.get('next')

        # 创建QQLogin工具的模型,next只需要传一次，之后QQ返回的url都会带着next
        oauth = OAuthQQ(client_id=settings.QQ_APP_ID, client_secret=settings.QQ_APP_KEY,
                        redirect_uri=settings.QQ_REDIRECT_URL, state=next)

        # 获取QQ登录页面
        loginUrl = oauth.get_qq_url()

        # 响应
        resp = {
            'code': RESP_CODE.OK,
            'respMsg': '响应成功',
            'loginUrl': loginUrl
        }
        print("resp：", resp)
        return http.JsonResponse(resp)


# QQ登录后的跳转回调
class QQAuthLoginView(View):
    def get(self, request):
        print('接收QQ登录回调地址参数: ', request)
        authorizationCode = request.GET.get('code')
        if not authorizationCode:
            return http.HttpResponseForbidden('腾讯code获取失败-_-')
        # 通过code(authorizationCode)获取accessToken
        oauth = OAuthQQ(client_id=settings.QQ_APP_ID, client_secret=settings.QQ_APP_KEY,
                        redirect_uri=settings.QQ_REDIRECT_URL)

        try:
            accessToken = oauth.get_access_token(authorizationCode)
            openid = oauth.get_open_id(accessToken)
            userid = request.GET.get('userid')
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('OAuth2.0认证失败')

        # 根据openid判断用户是否已经绑定过账号
        try:
            oauthUser = OauthQQUser.objects.get(openid=openid)
        except OauthQQUser.DoesNotexist:
            print("用户未绑定openid，跳转用户绑定页面（QQ登录）,进行绑定openid和userId")

            #  openid加密到前端
            secretToken = GenerateOpenidToken(userid,openid)
            print('secretToken: ',secretToken)
            deToken=TokenToJson(secretToken)
            print('deToken: ',deToken)

            # 将加密后的openid放入页面
            context = {'openid': secretToken}

            return render(request, 'users/oauth_callback.html', context)

        else:
            print('用户已绑定openid，登录并直接跳转next')
            # 注意：传入OauthQQUser模型类中user对象
            login(request, oauthUser.user)
            # 写入cookie缓存username
            response = redirect(reverse('contents:index'))
            response.set_cookie('username', oauthUser.user.username, max_age=3600 * 12 * 14)

            return response


# 保存QQ登录获取的openid和userid
class QQOauthSaveView(View):
    def post(self, request):
        print('saving')
